package com.example.project.Service.Impl;

import com.example.project.Service.CodeService;
import com.example.project.Service.CodeUtils;
import com.example.project.Service.PhoneService;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class PhoneServiceImpl implements PhoneService {

    @Autowired
    private CodeUtils codeUtils;

    @Value("${tencent.sms.account.secret_id}")
    private String SECRET_ID ;
    @Value("${tencent.sms.account.secret_key}")
    private String SECRET_KEY;
    @Value("${tencent.sms.account.sms_sdk_app_id}")
    private String SMS_SDK_APP_ID;
    @Value("${tencent.sms.account.template_id}")
    private String TEMPLATE_ID;
    @Value("${tencent.sms.account.sign_name}")
    private String SIGN_NAME;

    public int sendPhoneCode(String phone){
        Credential cred = new Credential(SECRET_ID, SECRET_KEY);
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint("sms.tencentcloudapi.com");
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);

        String[] phone_number = {"+86" + phone};
        String code = codeUtils.VerifyCode();
        String[] templateParams = {code};
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setSmsSdkAppid(SMS_SDK_APP_ID);
        sendSmsRequest.setTemplateID(TEMPLATE_ID);
        sendSmsRequest.setSign(SIGN_NAME);
        sendSmsRequest.setPhoneNumberSet(phone_number);
        sendSmsRequest.setTemplateParamSet(templateParams);

        try{
            client.SendSms(sendSmsRequest);
            codeUtils.setCode(phone,code);
            return 1;
        } catch (TencentCloudSDKException e){
            return 0;
        }
    }
}
